﻿
using Falafel.Model.Services;
using System;
using System.Data;
using System.Linq;
using System.ServiceModel.DomainServices.EntityFramework;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using Falafel.Services.Web.Models;

namespace Falafel.Services.Web.Services
{
    [RequiresAuthentication]
    [EnableClientAccess]
    public class OrderService : FalafelBaseService
    {
		public OrderService(User currentUser) : base(currentUser) { }

        [Invoke]
        public void MakeOrderCalifornia(int orderId)
        {
            var orderQuery = from o in GetOrders()
                             where o.ID == orderId
                             select o;

            Order order = orderQuery.FirstOrDefault();

            if (order == null)
            {
                throw new Exception("Cannot find order with an ID of " + orderId);
            }

            var stateQuery = from s in GetStates()
                             where s.Name.Equals("california", StringComparison.OrdinalIgnoreCase)
                             select new { s.ID };
            
            var stateQueryResults = stateQuery.FirstOrDefault();

            if (stateQueryResults == null)
            {
                throw new Exception("Cannot find state with a name of california");
            }

            int stateId = stateQueryResults.ID;

            order.StateID = stateId;
            SetAuditingFields(order, false);
            ObjectContext.SaveChanges();
        }

        public IQueryable<Order> GetOrders()
        {
            return ObjectContext.Orders.OrderBy( order => order.OrderDate );
        }

		public IQueryable<State> GetStates()
		{
			return ObjectContext.States.OrderBy(state => state.Name);
		}

		public IQueryable<FalafelUser> GetFalafelUsers()
		{
			return ObjectContext.FalafelUsers;
		}

		public IQueryable<Login> GetLogins()
		{
			return ObjectContext.Logins;
		}

		public void InsertOrder(Order order)
		{
			SetAuditingFields(order, true);
			if ((order.EntityState != EntityState.Detached))
			{
				ObjectContext.ObjectStateManager.ChangeObjectState(order, EntityState.Added);
			}
			else
			{
				ObjectContext.Orders.AddObject(order);
			}
		}

		public void UpdateOrder(Order currentOrder)
		{
			SetAuditingFields(currentOrder, false);
			ObjectContext.Orders.AttachAsModified(currentOrder, ChangeSet.GetOriginal(currentOrder));
		}

		public void DeleteOrder(Order order)
		{
			if ((order.EntityState == EntityState.Detached))
			{
				ObjectContext.Orders.Attach(order);
			}
			
            ObjectContext.Orders.DeleteObject(order);
		}
    }
}


